package com.dafau.ftp.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class ImagesArchiving {

	FTPClient ftpClient;

	public void login() {
		ftpClient = new FTPClient();
		try {
			ftpClient.connect("v1.ftp.upyun.com");
			ftpClient.login("dafau/dafau", "meiwenhui.com");
			ftpClient.changeWorkingDirectory("/");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public FTPFile[] getFtpFile(String path) throws IOException {
		ftpClient.changeWorkingDirectory(path);
		return ftpClient.listFiles(path);
	}

	public boolean hasChildren(String path) throws IOException {
		FTPFile[] ftpFiles = ftpClient.listFiles();
		return (ftpFiles == null || ftpFiles.length > 0) ? true : false;
	}

	public boolean moveFile(String from, String to) throws IOException {
		return ftpClient.rename(from, to);
	}
	
	public static void main(String[] args) throws IOException {
		ImagesArchiving ia = new ImagesArchiving();
		ia.login();
		String url = "http://dafau.b0.upaiyun.com";
		String sql = "insert into gr_photo(url) values ('%s');";
		StringBuffer sb = new StringBuffer();
		FTPFile[] ftpDirs = ia.getFtpFile("/");
		for (FTPFile ftpFile : ftpDirs) {
			FTPFile[] ftpFiles = ia.getFtpFile("/" + ftpFile.getName() + "/");
			for (FTPFile ftpFile2 : ftpFiles) {
				sb.append(String.format(sql, url + "/" + ftpFile.getName() + "/" + ftpFile2.getName()) + "\n");
			}
		}
		IOUtils.write(sb, new FileOutputStream(new File("c:/photo.sql")));
	}

}
